 'use client';

import React, { useState, useEffect } from 'react';
import { useParams, useRouter, useSearchParams } from 'next/navigation';
import { 
  PageContainer
} from '@ant-design/pro-components';
import { 
  Button, 
  Space, 
  message,
  Card,
  Tabs,
  Form
} from 'antd';
import { 
  ArrowLeftOutlined,
  EditOutlined,
  DollarOutlined,
  UploadOutlined,
  SaveOutlined
} from '@ant-design/icons';
import { OrderInfo, OrderStatus, ExperimentType, PaymentMethod, SampleShippingMethod } from '@/types/order';
import { OrderType } from '@/types/instrument';
import { useOverlayManager } from '@/hooks/useOverlayManager';
import ModifyOrderAmountModal from '../components/ModifyOrderAmountModal';
import UploadDataModal from '../components/UploadDataModal';
import OrderBasicForm from './components/OrderBasicForm';
import SampleShippingForm from './components/SampleShippingForm';
import MachineTimeForm from './components/MachineTimeForm';

type PageMode = 'create' | 'edit' | 'view';

const OrderDetailPage: React.FC = () => {
  const params = useParams();
  const router = useRouter();
  const searchParams = useSearchParams();
  const [form] = Form.useForm();
  const orderId = params.id as string;
  
  // 获取页面模式
  const mode: PageMode = orderId ? (searchParams.get('mode') as PageMode || 'view') : 'create';
  
  const [orderInfo, setOrderInfo] = useState<OrderInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('basic');
  const { openOverlay } = useOverlayManager();

  // 页面标题映射
  const pageTitleMap = {
    create: '新增订单',
    edit: '编辑订单',
    view: '订单详情'
  };

  // 模拟订单详情数据
  const mockOrderDetail: OrderInfo = {
    id: orderId,
    orderNumber: '000001',
    userId: '1',
    user: {
      id: '1',
      username: 'user001',
      phone: '18812341234',
      email: 'user001@example.com',
      realName: '李老师',
      role: 'level_1_user',
      status: 'normal',
      balance: 1000,
      isVerified: true,
      createdAt: '2024-01-01 10:00:00',
      updatedAt: '2024-01-01 10:00:00',
    },
    instrumentId: '1',
    instrument: {
      id: '1',
      name: '等离子体发射光谱仪(ICP-OES)',
      model: 'ICP-OES',
      category: 'analysis',
      status: 'available',
      location: '实验室A-101',
      description: '高精度等离子体发射光谱仪，适用于多元素分析',
      images: ['/images/instrument1.jpg'],
      specifications: {
        '检测元素': '70多种元素',
        '检出限': 'ppb级别',
        '精密度': '<1% RSD'
      },
      orderTypes: [],
      timeSlots: [],
      consumables: [],
      valueAddedServices: [],
      createdAt: '2024-01-01 10:00:00',
      updatedAt: '2024-01-01 10:00:00',
    },
    orderType: OrderType.SELF_OPERATION,
    experimentType: ExperimentType.NORMAL,
    status: OrderStatus.PENDING_REVIEW,
    reservationTime: [
      {
        start: '2025-03-28 10:30',
        end: '2025-03-28 11:30',
      },
      {
        start: '2025-03-29 10:30',
        end: '2025-03-29 11:30',
      }
    ],
    totalAmount: 2000.00,
    timeAmount: 1400.00,
    consumableAmount: 500.00,
    serviceAmount: 100.00,
    paymentMethod: PaymentMethod.PERSONAL_BALANCE,
    sampleInfo: '水样检测，需要检测重金属含量',
    sampleShippingMethod: SampleShippingMethod.SELF_DELIVERY,
    selectedConsumables: [
      { consumable: { id: '1', name: '耗材1', price: 500, description: '', unit: '', stock: 100 }, quantity: 1 }
    ],
    selectedServices: [
      { id: '1', name: '选择服务', price: 500, description: '' }
    ],
    dataFiles: [
      '实验数据1.xlsx',
      '实验报告.pdf'
    ],
    createdAt: '2025-03-28 09:00:00',
    updatedAt: '2025-03-28 10:30:00',
  };

  useEffect(() => {
    // 模拟加载订单详情
    const loadOrderDetail = async () => {
      setLoading(true);
      try {
        // TODO: 调用API获取订单详情
        await new Promise(resolve => setTimeout(resolve, 500));
        if (orderId && mode !== 'create') {
        setOrderInfo(mockOrderDetail);
          form.setFieldsValue(mockOrderDetail);
        }
      } catch {
        message.error('加载订单详情失败');
      } finally {
        setLoading(false);
      }
    };

    loadOrderDetail();
  }, [orderId, mode, form]);

  // 表单提交
  const handleSubmit = async (values: Record<string, unknown>) => {
    setLoading(true);
    try {
      console.log('表单数据:', values);
      // TODO: 调用API保存数据
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      if (mode === 'create') {
        message.success('订单创建成功');
      } else {
        message.success('订单更新成功');
      }
      
      router.push('/orders');
    } catch {
      message.error(`${mode === 'create' ? '创建' : '更新'}失败，请重试`);
    } finally {
      setLoading(false);
    }
  };

  // 处理订单操作
  const handleOrderAction = (action: string) => {
    message.success(`${action}操作成功`);
    // TODO: 刷新订单状态
  };

  // 切换到编辑模式
  const handleEdit = () => {
    const newUrl = `/orders/${orderId}?mode=edit`;
    router.push(newUrl);
  };

  // 修改订单金额
  const handleModifyAmount = async () => {
    if (!orderInfo) return;
    
    try {
      await openOverlay({
        name: "modify-amount-modal",
        Overlay: ModifyOrderAmountModal,
        props: {
          orderInfo: {
            id: orderInfo.id,
            orderNumber: orderInfo.orderNumber,
            orderAmount: orderInfo.orderAmount,
          },
          onSubmit: async (newAmount: number, remark: string) => {
            // TODO: 调用API修改订单金额
            console.log('修改订单金额:', { orderId: orderInfo.id, newAmount, remark });
            message.success('订单金额修改成功');
            // 重新加载订单信息
          },
          onClose: () => {
            // 关闭回调
          },
        },
        openProp: "open",
      });
    } catch (error) {
      console.error('修改订单金额失败:', error);
    }
  };

  // 上传数据
  const handleUploadData = async () => {
    if (!orderInfo) return;
    
    try {
      await openOverlay({
        name: "upload-data-modal",
        Overlay: UploadDataModal,
        props: {
          orderInfo: {
            id: orderInfo.id,
            orderNumber: orderInfo.orderNumber,
            experimentName: orderInfo.experimentName || '',
          },
          onSubmit: async (files: File[]) => {
            // TODO: 调用API上传数据
            console.log('上传数据:', { orderId: orderInfo.id, files });
            message.success('数据上传成功');
          },
          onClose: () => {
            // 关闭回调
          },
        },
        openProp: "open",
      });
    } catch (error) {
      console.error('上传数据失败:', error);
    }
  };

  // 获取操作按钮
  const getActionButtons = () => {
    if (mode === 'view' && orderInfo) {
    const buttons = [];

    // 根据状态显示不同操作
    switch (orderInfo.status) {
      case OrderStatus.PENDING_REVIEW:
        buttons.push(
          <Button
            key="approve"
            type="primary"
            onClick={() => handleOrderAction('通过')}
          >
            通过
          </Button>,
          <Button
            key="reject"
            onClick={() => handleOrderAction('驳回')}
          >
            驳回
          </Button>
        );
        break;

      case OrderStatus.CONFIRMED:
        buttons.push(
          <Button
            key="start"
            type="primary"
            onClick={() => handleOrderAction('上机')}
          >
            上机
          </Button>
        );
        break;

      case OrderStatus.IN_PROGRESS:
        buttons.push(
          <Button
            key="stop"
            type="primary"
            onClick={() => handleOrderAction('下机')}
          >
            下机
          </Button>
        );
        break;

      case OrderStatus.PENDING_SETTLEMENT:
        buttons.push(
          <Button
            key="settle"
            type="primary"
            onClick={() => handleOrderAction('结算')}
          >
            结算
          </Button>,
          <Button
            key="refund"
            onClick={() => handleOrderAction('退款')}
          >
            退款
          </Button>
        );
        break;
    }

    // 修改金额按钮
    if ([OrderStatus.CONFIRMED, OrderStatus.PENDING_SETTLEMENT].includes(orderInfo.status)) {
      buttons.push(
        <Button
          key="modify_amount"
          icon={<DollarOutlined />}
          onClick={handleModifyAmount}
        >
          修改金额
        </Button>
      );
    }

    // 上传数据按钮
    buttons.push(
      <Button
        key="upload"
        icon={<UploadOutlined />}
        onClick={handleUploadData}
      >
        上传数据
      </Button>
    );

      // 编辑按钮
      buttons.push(
        <Button
          key="edit"
          icon={<EditOutlined />}
          onClick={handleEdit}
        >
          编辑
      </Button>
    );

    return buttons;
    }

    // 编辑和新增模式的按钮
    return [
      <Button key="cancel" onClick={() => router.back()}>
        取消
      </Button>,
      <Button 
        key="save"
        type="primary" 
        loading={loading}
        icon={<SaveOutlined />}
        onClick={() => form.submit()}
      >
        {mode === 'create' ? '创建' : '保存'}
      </Button>
    ];
  };

  // Tab项配置
  const tabItems = [
    {
      key: 'basic',
      label: '预约信息',
      children: (
        <OrderBasicForm 
          form={form}
          mode={mode}
          initialValues={(orderInfo as unknown as Record<string, unknown>) || {}}
          onSubmit={handleSubmit}
        />
      ),
    },
    {
      key: 'shipping',
      label: '样品邮寄',
      children: (
        <SampleShippingForm 
          form={form}
          mode={mode}
          initialValues={(orderInfo as unknown as Record<string, unknown>) || {}}
          onSubmit={handleSubmit}
        />
      ),
    },
    {
      key: 'schedule',
      label: '上下机时间',
      children: (
        <MachineTimeForm 
          form={form}
          mode={mode}
          initialValues={(orderInfo as unknown as Record<string, unknown>) || {}}
          onSubmit={handleSubmit}
        />
      ),
    },
  ];

  if (loading) {
    return <PageContainer loading />;
  }

  return (
    <PageContainer
      title={
        <Space>
          <Button 
            type="text" 
            icon={<ArrowLeftOutlined />} 
            onClick={() => router.back()}
          >
            返回
          </Button>
          <span>{pageTitleMap[mode]}</span>
          {mode === 'view' && orderInfo && (
            <span style={{ fontSize: '16px', color: '#666' }}>
              - {orderInfo.orderNumber}
            </span>
          )}
        </Space>
      }
      extra={
        <Space>
          {getActionButtons()}
        </Space>
      }
    >
      <Card>
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={tabItems}
        />
      </Card>


    </PageContainer>
  );
};

export default OrderDetailPage;